package com.dwxt.mall.admin.service;

import com.dwxt.common.base.AdminUserType;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.util.MD5Utils;
import com.dwxt.mall.admin.service.feign.AdminUserService;
import com.dwxt.mall.dao.TrainHallMapper;
import com.dwxt.mall.entity.TrainHall;
import com.dwxt.mall.entity.TrainHallExample;
import com.dwxt.mall.entity.dto.TrainHallDTO;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class TrainHallServiceAdmin {
    @Autowired
    private TrainHallMapper trainHallMapper;

    @Autowired
    private AdminUserService adminUserService;

    @Transactional
    public BaseResult createOrUpdateHall(TrainHallDTO trainHall) {
        String password = trainHall.getPassword();
        if (StringUtils.isNotBlank(password)) {
            trainHall.setPassword(MD5Utils.MD5Encode(password));
        }
        List<Integer> roleIds = new ArrayList<>();
        roleIds.add(1);
        if (trainHall.getId() == null) {
            //创建一个后台用户
            BaseResult baseResult = adminUserService.createOrUpdateUser(null, trainHall.getUsername(), trainHall.getPhone(),
                    password, trainHall.getType(), roleIds);
            if (baseResult.getStatus() != 200) {
                return baseResult;
            }
            //创建一个场馆信息
            if (AdminUserType.MALL_TRAIN.equals(String.valueOf(trainHall.getType()))) {
                trainHall.setId(JSONObject.fromObject(baseResult.getData()).getInt("id"));
                trainHallMapper.insertSelective(trainHall);
            }
        } else {
            trainHallMapper.updateByPrimaryKeySelective(trainHall);
            adminUserService.createOrUpdateUser(trainHall.getId(), trainHall.getUsername(),
                    trainHall.getPhone(), password, null, roleIds);
        }
        return BaseResult.ok();
    }

    public TrainHall selectHallByKey(Integer id) {
        return trainHallMapper.selectByPrimaryKey(id);
    }

    public void delete(Integer[] id) {
        TrainHallExample example = new TrainHallExample();
        example.createCriteria().andIdIn(Arrays.asList(id));
        trainHallMapper.deleteByExample(example);
    }
}
